#include "history.h"
#include "global.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

history_entry CSSH_history;


void add_history_entry( const char * cmdline)
{
  unsigned char pos;
  assert ( cmdline != 0 );
  pos = CSSH_history.last + 1;
  pos = pos %20;
  strcpy(CSSH_history.entries[pos], cmdline );
  
  CSSH_history.last = pos;
}


void list_history_entries()
{
  unsigned char p;
  for ( p =1; p<= 20; p++)
    {
      if ( CSSH_history.entries[(CSSH_history.last+p)%20][0] != '\0')
	printf("[%i] %s" , (CSSH_history.last+p)%20 , CSSH_history.entries[(CSSH_history.last+p)%20]);
    }
}

/*Save history to file in home directory*/
void save_to_file( const char * fname)
{
  char path[50];
  FILE * pFile;
  unsigned char n ;
  
  /*build history file path and name*/
  strcpy(path , CSSH_globals.hom_path);
  strncat(path, "/" , 1);
  strncat(path, fname, 50);

  pFile = fopen (path,"w");
  if (pFile!=0)
    {
      /*put all entries from history in file*/
      for (n = 1 ;n <= 20 ; n++)
	{
	  if ( CSSH_history.entries[(CSSH_history.last+n)%20][0] != '\0')
	    fputs (CSSH_history.entries[(CSSH_history.last+n)%20],pFile);
	}
      fclose (pFile);
    }
  
}


void read_from_file( const char * fname )
{
  char path[50];
  char entry[512];
  FILE * pFile;
  
  /*build history file path and name*/
  strcpy(path , CSSH_globals.hom_path);
  strncat(path, "/" , 1);
  strncat(path, fname, 50);

  pFile = fopen (path,"r");
  CSSH_history.last = 0 ; 
  if ( pFile != 0 )
    {
      while ( fgets(entry,512,pFile))
	{
	  add_history_entry( entry);
	}
	fclose (pFile);
    } 
    
}

const char * get_last_cmd(void )
{
  return CSSH_history.entries[CSSH_history.last];
}

const char * get_cmd_nb(unsigned char nb)
{

  return (CSSH_history.entries[nb]);
}
